#!/usr/bin/env python3
# @Date    : 2022-02-28
# @Author  : Bright (brt2@qq.com)
# @Link    : https://gitee.com/brt2
# @Version : 0.1.0

import os
from tornado import web, httpserver, ioloop
from tornado.options import define, options
import tornado.options

define("port", type=int, default=1213, help="run on the given port")
define("user", default='root')
define("passwd", default='123123')

html = '''<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, width=device-width" />
 <style type="text/css">
    input {font:11px Verdana;BACKGROUND: #FFFFFF;height: 18px;border: 1px solid #666666;}
 </style>
</head>
<body>
    <form method="POST" action="">
    <span style="font:11px Verdana;">密码: </span><input name="pwd" type="password" size="20">
    <input type="submit" value="登陆">
    </form>
</body>
</html>'''

upload = '''<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, width=device-width" />
  <style type="text/css">
    body,table{color:#444444;font-family:PingFangSC-Regular, Helvetica, 'Helvetica Neue', 'Segoe UI', 'Hiragino Sans GB', 'Source Han Sans CN', 'Microsoft YaHei', STHeiti, 'WenQuanYi Micro Hei', sans-serif;font-size:12px;text-align:justify;background-color:#FFFFFF;;word-wrap:break-word;word-break: normal;word-break:break-all;}
#main {
    width: 70%;
    margin: 0 auto;
}
form, table, input, textarea, dl, dt, dd{outline:none}
a{color:#000;text-decoration:none;}
/* 小屏幕CSS*/
@media screen and (max-width:630px){
#main{padding: 2px;height: 400px;width: 100%;margin-top: 0px;margin-right: auto;margin-bottom: 0px;margin-left: auto;}
}
  </style>
</head>
<body>
<div id="main">
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="Filedata" />
<input type="submit" value="上传" name="submit" />
</form></div>
</body>
</html>'''


class IndexPageHandler(web.RequestHandler):
    def get(self, name):
        # self.request.remote_ip
        self.write(html)

    def post(self, *arg, **kwargs):
        self.redirect('/list')

# 文件上传


class UploadHandler(web.RequestHandler):
    def get(self):
        self.write(upload)

    def post(self, *args, **kwargs):
        file_metas = self.request.files
        self.write(file_metas['Filedata'][0]['filename'])
        # for meta in file_metas:
        meta = file_metas['Filedata'][0]
        file_name = meta['filename']
        file_name = os.path.join(os.getcwd() + os.sep + "file", file_name)
        # print file_name
        with open(file_name, 'wb') as up:
            up.write(meta['body'])
        self.redirect('/upload')


"""
<ul>
    {% for file in files %}
    <li>
        <a href="{{ (request.path + '/' if request.path != '/' else '') + file }}">
            {{ (request.path + '/' if request.path != '/' else '') + file }}
        </a>
    </li>
    {% endfor %}
</ul>"""


class ViewListHandler(web.RequestHandler):
    """ 浏览列表 """

    def get(self):
        d = self.get_argument('d', os.getcwd())
        flist = {"root": os.listdir(root)}
        print(">>>", flist)
        self.write(flist)


class DownloadHandler(web.RequestHandler):
    def get(self):
        filename = self.get_argument('filename')
        print(filename)
        # http头 浏览器自动识别为文件下载
        self.set_header('Content-Type', 'application/octet-stream')
        # 下载时显示的文件名称
        #self.set_header('Content-Disposition', 'attachment; filename=%s'%filename)
        self.set_header('Content-Disposition',
                        ('attachment; filename=%s' % filename).encode('utf-8'))
        filename = options.user + filename
        buff = 1024 * 1024 * 2
        data = ''
        with open(filename, 'rb') as f:
            while True:
                data = f.read(buff)
                if not data:
                    break
                self.write(data)
        # # 记得有finish哦
        self.finish()


class BaseHandler(web.RequestHandler):
    def get(self):
        # self.write_error(404)
        self.write('该网页不存在!')

    def write_error(self, status_code, **kwargs):
        if status_code == 404:
            # self.render('public/404.html')
            self.write('该网页不存在!')
        elif status_code == 500:
            # self.render('public/500.html')
            self.write('该网页不存在!')
        else:
            #self.write('error:' + str(status_code))
            pass


settings = {
    'debug': True,
    # 'template_path': os.path.dirname(__file__) + '/template',
    'template_path': os.path.dirname(__file__),
    'static_path': "static",
    'default_handler_class': BaseHandler
}

# 路由
application = web.Application([
    (r'/list$', ViewListHandler),
    (r'/upload$', UploadHandler),
    (r'/d$', DownloadHandler),
    (r'/(?P<name>[^/]*?)', IndexPageHandler),
    (r".*", BaseHandler),
], **settings)

# (r"/(apple-touch-icon.png)", web.StaticFileHandler, dict(path=settings['static_path'])

if __name__ == '__main__':
    options.parse_command_line()
    http_server = httpserver.HTTPServer(application)
    # 监听端口
    application.listen(1111)
    # print('http://127.0.0.1:8080/')
    ioloop.IOLoop.current().start()
